package com.chengqj;

import com.chengqj.service.IOrderService;
import com.chengqj.service.IUserService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * The type Tcc transaction service.
 *
 * @author zhangsen
 */
@Service
public class TccTransactionService {
    @DubboReference
    private IUserService userService;
    @Autowired
    private IOrderService orderService;

    /**
     * 发起分布式事务
     *
     * @return string string
     */
    @GlobalTransactional
    public String doTransactionCommit(){
        //第一个TCC 事务参与者
        boolean result = orderService.prepare(null, "123");
        if(!result){
            throw new RuntimeException("TccActionOne failed.");
        }
        result = userService.prepare(null, "123");
        if(!result){
            throw new RuntimeException("TccActionTwo failed.");
        }
        return RootContext.getXID();
    }

    /**
     * Do transaction rollback string.
     *
     * @return the string
     */
    @GlobalTransactional
    public String doTransactionRollback(){
        //第一个TCC 事务参与者
        boolean result = orderService.prepare(null, "123");
        if(!result){
            throw new RuntimeException("TccActionOne failed.");
        }
        result = userService.prepare(null, "123");
        if(!result){
            throw new RuntimeException("TccActionTwo failed.");
        }
        throw new RuntimeException("transacton rollback");
    }

    /**
     * Sets tcc action one.
     *
     * @param userService the tcc action one
     */
    public void setTccActionOne(IUserService userService) {
        this.userService = userService;
    }

    /**
     * Sets tcc action two.
     *
     * @param orderService the tcc action two
     */
    public void setTccActionTwo(IOrderService orderService) {
        this.orderService = orderService;
    }
}
